All files / src/app/api/dev/tickets/[id]/link route.ts

0% Statements 0/191
100% Branches 0/0
0% Functions 0/1
0% Lines 0/191

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192                                                                                                                                                                                                                                                                                                                                                                                               
export const dynamic = "force-dynamic";

/**
 * Dev Ticket Linking API
 * POST /api/dev/tickets/[id]/link - Link two tickets
 * DELETE /api/dev/tickets/[id]/link - Remove a ticket link
 */

import { NextRequest, NextResponse } from 'next/server';
import { Session } from "next-auth";
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import type { AuthenticatedUser } from '@/lib/api/middleware/types';
import { prisma } from '@/lib/prisma';
import { CreateDevTicketLinkSchema } from '@/lib/validation/dev-ticket-schemas';
import { createTicketHistory } from '@/lib/dev-ticket';
import { logger } from '@/lib/logging';
import { TICKET_LINK_TYPE_CONFIG } from '@/constants/dev-ticket';
import { TicketLinkType } from '@/types/dev-ticket';

interface RouteParams {
  params: Promise<{ id: string }>;
}

async function handlePost(
  request: NextRequest,
  context: RouteContext | undefined,
  session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id: sourceTicketId } = await (context as RouteParams).params;
  const body = await request.json();

  const validationResult = CreateDevTicketLinkSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation("Invalid link data", validationResult.error.flatten().fieldErrors);
  }

  const { targetTicketId, linkType } = validationResult.data;

  // Can't link a ticket to itself
  if (sourceTicketId === targetTicketId) {
    throw ApiError.badRequest('Cannot link a ticket to itself');
  }

  // Verify source ticket exists
  const sourceTicket = await prisma.devTicket.findUnique({
    where: { id: sourceTicketId },
    select: { id: true, ticketNumber: true }});

  if (!sourceTicket) {
    throw ApiError.notFound('Source ticket not found');
  }

  // Verify target ticket exists
  const targetTicket = await prisma.devTicket.findUnique({
    where: { id: targetTicketId },
    select: { id: true, ticketNumber: true }});

  if (!targetTicket) {
    throw ApiError.notFound('Target ticket not found');
  }

  // Check if this exact link already exists
  const existingLink = await prisma.devTicketLink.findUnique({
    where: {
      sourceTicketId_targetTicketId_linkType: {
        sourceTicketId,
        targetTicketId,
        linkType}}});

  if (existingLink) {
    throw ApiError.badRequest('This link already exists');
  }

  // Create the link
  const link = await prisma.devTicketLink.create({
    data: {
      sourceTicketId,
      targetTicketId,
      linkType,
      createdById: user.id},
    include: {
      sourceTicket: {
        select: { id: true, ticketNumber: true, title: true, status: true }},
      targetTicket: {
        select: { id: true, ticketNumber: true, title: true, status: true }},
      createdBy: {
        select: { id: true, name: true }}}});

  // Record in history for both tickets
  const linkDescription = `${TICKET_LINK_TYPE_CONFIG[linkType as TicketLinkType].label} ${targetTicket.ticketNumber}`;
  await createTicketHistory(
    sourceTicketId,
    user.id,
    'linked',
    'link',
    null,
    linkDescription
  );

  const inverseLinkDescription = `${TICKET_LINK_TYPE_CONFIG[linkType as TicketLinkType].inverseLabel} ${sourceTicket.ticketNumber}`;
  await createTicketHistory(
    targetTicketId,
    user.id,
    'linked',
    'link',
    null,
    inverseLinkDescription
  );

  logger.info(`Linked tickets ${sourceTicket.ticketNumber} and ${targetTicket.ticketNumber}`, {
    category: 'DEV_TICKETS',
    sourceTicketId,
    targetTicketId,
    linkType,
    userId: user.id});

  return createdResponse(link);
}

async function handleDelete(
  request: NextRequest,
  context: RouteContext | undefined,
  session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id: sourceTicketId } = await (context as RouteParams).params;
  const { searchParams } = new URL(request.url);
  const linkId = searchParams.get('linkId');

  if (!linkId) {
    throw ApiError.badRequest('Link ID is required');
  }

  // Find the link
  const link = await prisma.devTicketLink.findUnique({
    where: { id: linkId },
    include: {
      sourceTicket: { select: { ticketNumber: true } },
      targetTicket: { select: { ticketNumber: true } }}});

  if (!link) {
    throw ApiError.notFound('Link not found');
  }

  // Verify the link belongs to this ticket
  if (link.sourceTicketId !== sourceTicketId && link.targetTicketId !== sourceTicketId) {
    throw ApiError.badRequest('Link does not belong to this ticket');
  }

  // Delete the link
  await prisma.devTicketLink.delete({
    where: { id: linkId }});

  // Record in history for both tickets
  await createTicketHistory(
    link.sourceTicketId,
    user.id,
    'unlinked',
    'link',
    link.targetTicket.ticketNumber,
    null
  );

  await createTicketHistory(
    link.targetTicketId,
    user.id,
    'unlinked',
    'link',
    link.sourceTicket.ticketNumber,
    null
  );

  logger.info(`Unlinked tickets ${link.sourceTicket.ticketNumber} and ${link.targetTicket.ticketNumber}`, {
    category: 'DEV_TICKETS',
    linkId,
    userId: user.id});

  return successResponse({ message: 'Link removed successfully' });
}

export const POST = withErrorHandling(withAdmin(handlePost));
export const DELETE = withErrorHandling(withAdmin(handleDelete));